﻿/**
 * 通用js方法封装处理
 */

const baseURL = process.env.VUE_APP_BASE_API

// 日期格式化
export function parseTime(time, pattern) {
	if (arguments.length === 0 || !time) {
		return null
	}
	const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
	let date
	if (typeof time === 'object') {
		date = time
	} else {
		if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
			time = parseInt(time)
		} else if (typeof time === 'string') {
			time = time.replace(new RegExp(/-/gm), '/');
		}
		if ((typeof time === 'number') && (time.toString().length === 10)) {
			time = time * 1000
		}
		date = new Date(time)
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	}
	const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key]
		// Note: getDay() returns 0 on Sunday
		if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
		if (result.length > 0 && value < 10) {
			value = '0' + value
		}
		return value || 0
	})
	return time_str
}

// 表单重置
export function resetForm(refName) {
	if (this.$refs[refName]) {
		this.$refs[refName].resetFields();
	}
}

//年月日格式
export function yearMouthDay(data) {
	var time = new Date(data);
    var year = time.getFullYear();
    var month = time.getMonth()+1;
    var date = time.getDate();
   console.log(year+'-'+add0(month)+'-'+add0(date))
	return year+'-'+add0(month)+'-'+add0(date)

}
function add0(m){return m<10?'0'+m:m }


// 添加日期范围
export function addDateRange(params, dateRange) {
	var search = params;
	search.beginTime = "";
	search.endTime = "";
	if (null != dateRange && '' != dateRange) {
		search.beginTime = this.dateRange[0];
		search.endTime = this.dateRange[1];
	}
	return search;
}

// 回显数据字典
export function selectDictLabel(datas, value) {
	var actions = [];
	Object.keys(datas).some((key) => {
		if (datas[key].dictValue == ('' + value)) {
			actions.push(datas[key].dictLabel);
			return true;
		}
	})
	return actions.join('');
}

// 回显数据字典（字符串数组）
export function selectDictLabels(datas, value, separator) {
	var actions = [];
	var currentSeparator = undefined === separator ? "," : separator;
	var temp = value.split(currentSeparator);
	Object.keys(value.split(currentSeparator)).some((val) => {
		Object.keys(datas).some((key) => {
			if (datas[key].dictValue == ('' + temp[val])) {
				actions.push(datas[key].dictLabel + currentSeparator);
				return true;
			}
		})
		return true;
	})
	return actions.join('').substring(0, actions.join('').length - 1);
}

// 通用下载方法
export function download(fileName) {
	window.location.href = fileName;
}

// 字符串格式化(%s )
export function sprintf(str) {
	var args = arguments, flag = true, i = 1;
	str = str.replace(/%s/g, function () {
		var arg = args[i++];
		if (typeof arg === 'undefined') {
			flag = false;
			return '';
		}
		return arg;
	});
	return flag ? str : '';
}

// 转换字符串，undefined,null等转化为""
export function praseStrEmpty(str) {
	if (!str || str == "undefined" || str == "null") {
		return "";
	}
	return str;
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(data, id, parentId, children) {
	id = id || 'id'
	parentId = parentId || 'parentId'
	children = children || 'children'
	let result = [];
	data = JSON.parse(JSON.stringify(data))
	if (!Array.isArray(data)) {
		return result
	}
	data.forEach(item => {
		delete item[children];
	});
	let map = {};
	data.forEach(item => {
		map[item[id]] = item;
	});
	data.forEach(item => {
		let parent = map[item[parentId]];
		if (parent) {
			parent[children] || (parent[children] = [])
			parent[children].push(item);
		} else {
			result.push(item);
		}
	});
	return result;
}

/**
 * 判断字符串是否为空
 * @param {*} str 传入字符串
 */
export function strIsNullOrEmpty(str) {
  if( str == null){
    return true;
  }
  if ( str == "" ){
    return true;
  }
  var regu = "^[ ]+$";
  var re = new RegExp(regu);
  return re.test(str);
}

/**
 * 判断字符串是否不为空
 * @param {*} str 传入字符串
 */
 export function strIsNotNullOrEmpty(str) {
  return !strIsNullOrEmpty(str);
}

/**
 * 判断值是否为整型数字
 * @param {*} val 传入值
 */

export function isIntNum(val){
  //正整数
  var regPos = /^\d+(\.\d+)?$/;
  if(regPos.test(val)){
      return true;
  }else{
      return false;
  }
}

/**
 * 判断数组是否为空
 * @param {*} array 传入值
 */
export function arrIsNotEmpty(array){
  return !arrIsEmpty(array);
}

/**
 * 判断数组是否不为空
 * @param {*} array 传入值
 */
 export function arrIsEmpty(array){
  return array == undefined || array.length <= 0;
}

export function formatDate (date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }
  for (let k in o) {
     if (new RegExp(`(${k})`).test(fmt)) {
       let str = o[k] + ''
       fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : padLeftZero(str))
     }
   }
   return fmt
 }

export function getNowDate(){
   return new Date(formatDate(new Date((new Date()).getTime() + 3600 * 1000 * 24), 'yyyy-MM-dd 00:00:00'));
 }

export function addDayDate(vDate, days){
  if(vDate == null){
    return null;
  }
  var tmpDate = new Date(vDate.getTime());
  tmpDate.setDate(vDate.getDate() + days);
  return tmpDate;
}

export function addMonthDate(vDate, months){
  if(vDate == null){
    return null;
  }
  var tmpDate = new Date(vDate.getTime());
  tmpDate.setMonth(vDate.getMonth() + months);
  return tmpDate;
}

 function padLeftZero (str) {
   return ('00' + str).substr(str.length)
 }

 export function inMobile(){
   let ua = navigator.userAgent.toLowerCase();
   let reg = /ipad|iphone|midp|rv:1.2.3.4|ucweb|android|windows ce|vivobrowser|huaweibrowser|heytapbrowser|sogoumobilebrowser|miuibrowser|mqqbrowser|windows mobile/
   return reg.test(ua)
 }

/**
 * 生成随机文件名称
 * 规则八位随机字符，加下划线连接时间戳
 */
 export const getFileNameUUID = () => {
	function rx() {
	  return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
	}
	return `${+new Date()}_${rx()}${rx()}`
  }
  
  